<template>
    <div>
      <el-tooltip :content="noticeContent" effect="dark" placement="bottom">
        <el-badge :value="noticeCount" class="right-menu-item hover-effect" :class="{ 'badge-custom': noticeCount > 0 }">
          <i class="el-icon-message-solid" @click="toNoticePage"></i>
        </el-badge>
      </el-tooltip>
    </div>
  </template>
  
  <script>
  import { listWbNoticeMessage } from "@/api/websocket/WbNoticeMessage";
  
  export default {
    name: "InfoBell",
    props: {
      refreshNoticeCount: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        noticeContent: "", // 通知内容
        noticeCount: 0,    // 通知数量
        socket: null,       // WebSocket 实例
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          content: null,
          type: null,
          senderId: null,
          senderName: null,
          receiverId: this.$store.state.user.id,
          receiverName: null,
          isRead: null,
          readTime: null,
          priority: null,
          targetUrl: null,
          bizType: null,
          bizId: null
        },
      };
    },
    created() {
      this.getList();
    },
    mounted() {
      this.initWebSocket();
    },
    beforeDestroy() {
      this.closeWebSocket();
    },
    watch: {
      refreshNoticeCount(val) {
        if (val) {
          this.getList();
        }
      }
    },
    methods: {
      /**---------------------websocket专栏-------------------- */
      /** 初始化/连接 WebSocket */
      initWebSocket() {
        // const token  // 需要鉴权
        const currentUserId = this.$store.state.user.id;
        const currentUserNickName = this.$store.state.user.nickName;
        const wsUrl = `ws://localhost:8080/websocket/pushMessage?userId=${currentUserId}&nickName=${currentUserNickName}`; // 替换为你的 WebSocket 地址
        this.socket = new WebSocket(wsUrl);
  
        this.socket.onopen = () => {
          console.log("头部导航消息铃铛-WebSocket 连接已建立");
          this.startHeartbeat();//启用心跳机制
        };
  
        this.socket.onmessage = (event) => {
          try {
            const msg = JSON.parse(event.data);
            if (msg.type === "pong") {
              console.log("收到心跳 pong");
              return;
            }
          } catch (e) {
            // 非 JSON 消息，继续执行
          }
          this.getList();
        };
  
        this.socket.onerror = (error) => {
          console.error("头部导航消息铃铛-WebSocket 发生错误:", error);
        };
  
        this.socket.onclose = () => {
          console.log("头部导航消息铃铛-WebSocket 已关闭");
          this.stopHeartbeat();
          this.tryReconnect();
        };
      },
      /** 关闭 WebSocket */
      closeWebSocket() {
        if (this.socket) {
          this.socket.close();
          this.socket = null;
        }
        this.stopHeartbeat();
        if (this.reconnectTimer) {
          clearInterval(this.reconnectTimer);
          this.reconnectTimer = null;
        }
      },
      /** 启动心跳 */
      startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
          if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify({ type: "ping" }));
            console.log("发送心跳 ping");
          }
        }, 30000); // 每 30 秒
      },

      /** 停止心跳 */
      stopHeartbeat() {
        if (this.heartbeatTimer) {
          clearInterval(this.heartbeatTimer);
          this.heartbeatTimer = null;
        }
      },

      /** 尝试重连 */
      tryReconnect() {
        if (this.reconnectTimer) return;
        this.reconnectTimer = setInterval(() => {
          console.log("尝试重连 InfoBell-WebSocket...");
          this.initWebSocket();
          if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
          }
        }, 5000); // 每 5 秒重连一次
      },
      /** -------------------------- 业务处理专栏---------------------- */
      /** 查询通知信息框列表 */
      getList() {
        this.queryParams.isRead = 0;
        listWbNoticeMessage(this.queryParams).then(response => {
          this.noticeCount = response.total;
          this.noticeContent = `您有${this.noticeCount}条未读的信息`;
        })
      },
      /** 跳转到通知页面 */
      toNoticePage() {
        this.$router.push("/websocket/pushMessage");
      },
    },
    
  };
  </script>
  
  <style lang="scss" scoped>
  ::v-deep .el-badge__content {
    margin-top: 9px;
    margin-right: 1px;
  }
  
  .badge-custom {
    animation: blink-animation 0.5s infinite alternate;
  }
  
  @keyframes blink-animation {
    0% {
      opacity: 1;
    }
    100% {
      opacity: 0.1;
    }
  }
  </style>
  